﻿using System;
using System.Reflection;

namespace 多协议通信平台.Base
{
    public static class PropertyHelper
    {
        /// <summary>
        /// 将源对象的属性值拷贝到目标对象（同名且类型兼容的属性）
        /// </summary>
        /// <typeparam name="TSource">源对象类型</typeparam>
        /// <typeparam name="TTarget">目标对象类型</typeparam>
        /// <param name="source">源对象实例</param>
        /// <param name="target">目标对象实例</param>
        public static void CopyProperties<TSource, TTarget>(TSource source, TTarget target)
        {
            if (source == null || target == null)
                throw new ArgumentNullException("源对象实例与目标对象实例不能为空");

            Type sourceType = typeof(TSource);
            Type targetType = typeof(TTarget);

            // 遍历目标对象的所有属性
            foreach (PropertyInfo targetProperty in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                // 查找源对象中同名且可读的属性
                PropertyInfo sourceProperty = sourceType.GetProperty(
                    targetProperty.Name,
                    BindingFlags.Public | BindingFlags.Instance
                );

                if (sourceProperty == null || !sourceProperty.CanRead)
                    continue; // 源对象没有该属性或不可读

                // 检查属性类型是否兼容（相同类型，或目标类型是源类型的基类/接口）
                if (targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                {
                    // 获取源属性值并赋值给目标属性
                    object value = sourceProperty.GetValue(source);
                    if (targetProperty.CanWrite)
                    {
                        targetProperty.SetValue(target, value);
                    }
                }
            }
        }
    }
}
